package com.jtjrenren.android.taxi.driver.core.order.details;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.vi.VDeviceAPI;
import com.jtjrenren.android.taxi.driver.Constants;
import com.jtjrenren.android.taxi.driver.base.BaseApplication;
import com.jtjrenren.android.taxi.driver.bean.Order;
import com.jtjrenren.android.taxi.driver.bean.event.ControlCenterEvent;
import com.jtjrenren.android.taxi.driver.R;
import com.jtjrenren.android.taxi.driver.bean.NavAddressInfo;
import com.jtjrenren.android.taxi.driver.bean.control.CmdCommonResponse;
import com.jtjrenren.android.taxi.driver.bean.control.CmdZxQxDdResponse;
import com.jtjrenren.android.taxi.driver.bean.event.OrderCostEvent;
import com.jtjrenren.android.taxi.driver.bean.event.OrderDetailsEvent;
import com.jtjrenren.android.taxi.driver.manger.AppManger;
import com.jtjrenren.android.taxi.driver.manger.TtsManger;
import com.jtjrenren.android.taxi.driver.manger.push.cmd.ControlCmd;
import com.jtjrenren.android.taxi.driver.manger.push.cmd.Protocl;
import com.library.mvp.presenter.MvpBasePresenter;
import com.library.utils.LogUtil;
import com.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * Created by Administrator on 2016/8/29.
 */

public class OrderDetailsPresenterImpl extends MvpBasePresenter<OrderDetailsView, OrderDetailsInteractor> implements OrderDetailsPresenter {
    private NavAddressInfo startAddress, endAddress;
    private Order order;
    private RoutePlanSearch routePlanSearch;

    public OrderDetailsPresenterImpl(OrderDetailsView view) {
        super(view);
    }


    @Override
    public OrderDetailsInteractor createInteractor() {
        return new OrderDetailsInteractorImpl();
    }

    @Override
    public void init(String orderID) {
        EventBus.getDefault().register(this);
        initRoute();

        if (StringUtils.isEmpty(orderID))
            return;

        if (AppManger.getInstance().currentLocation != null)
            view.animRefreshMapTarget(new LatLng(AppManger.getInstance().currentLocation.getLatitude(), AppManger.getInstance().currentLocation.getLongitude()));

        getOrderDetails(orderID);
    }


    @Override
    public void destory() {
        EventBus.getDefault().unregister(this);
        if (routePlanSearch != null)
            routePlanSearch.destroy();
        routePlanSearch = null;
        VDeviceAPI.unsetNetworkChangedCallback();
    }

    @Override
    public void startYYD() {
        TtsManger.getInstance().speak("开始预约单");
        AppManger.getInstance().sendMsg(ControlCmd.getQjCkCmd(order.getOrderID()));
        view.showTipProg(AppManger.getInstance().getResourceString(R.string.shujutijiaozhongqingshaohou));
    }

    @Override
    public void jdCk() {
        if (AppManger.getInstance().isYzc())
            TtsManger.getInstance().speak("开始计费");
        else
            TtsManger.getInstance().speak("乘客已上车");

        AppManger.getInstance().sendMsg(ControlCmd.getQrCkScCmd(order.getOrderID()));
        view.showTipProg(AppManger.getInstance().getResourceString(R.string.shujutijiaozhongqingshaohou));
    }

    @Override
    public void ddMdd() {
        if (AppManger.getInstance().isYzc()) {
            TtsManger.getInstance().speak("结束计费");
            view.stopRefreshOrderCost();
        } else
            TtsManger.getInstance().speak("目的地到了");

        view.showTipProg(AppManger.getInstance().getResourceString(R.string.shujutijiaozhongqingshaohou));

        AppManger.getInstance().sendMsg(ControlCmd.getOrderFinishCmd(order.getOrderID()));
    }

    @Override
    public void clickCancleOrder() {
        TtsManger.getInstance().speak(AppManger.getInstance().getResourceString(R.string.quxiaodingdantishi));
        view.showCancleOrderTip();
    }

    @Override
    public void cancleOrder() {
        view.showTipProg(AppManger.getInstance().getResourceString(R.string.shujutijiaozhongqingshaohou));
        TtsManger.getInstance().stop();

        String orderCancleCmd = ControlCmd.getOrderCancleCmd(order.getOrderID(), 0);
        AppManger.getInstance().sendMsg(orderCancleCmd);
    }

    @Override
    public void getOrderDetails(String orderID) {
        if (StringUtils.isEmpty(orderID))
            return;
        view.showTipProg("数据加载中，请稍候...");
        interactor.getOrderDetails(orderID);
    }

    @Override
    public String getPassgerPhone() {
        return order.getPassgerPhone();
    }


    @Override
    public void searchRoute(LatLng startLL, LatLng endLL) {
        if (routePlanSearch == null)
            return;
        PlanNode start = PlanNode.withLocation(startLL);
        PlanNode end = PlanNode.withLocation(endLL);
        routePlanSearch.drivingSearch((new DrivingRoutePlanOption())
                .from(start).to(end));
    }

    @Override
    public void getOrderCost() {
        if (order == null)
            return;
        interactor.getOrderCost(order.getOrderID());
    }

    @Override
    public LatLng getStart() {
        LatLng latLng = null;
        if (startAddress != null&&!StringUtils.isEmpty(startAddress.getLat())&&!StringUtils.isEmpty(startAddress.getLng()))
            latLng = new LatLng(Double.parseDouble(startAddress.getLat()), Double.parseDouble(startAddress.getLng()));
        return latLng;
    }

    @Override
    public LatLng getEnd() {
        LatLng latLng = null;
        if (endAddress != null&&!StringUtils.isEmpty(endAddress.getLat())&&!StringUtils.isEmpty(endAddress.getLng()))
            latLng = new LatLng(Double.parseDouble(endAddress.getLat()), Double.parseDouble(endAddress.getLng()));
        return latLng;
    }

    //处理定位返回事件
    @Subscribe
    public void handLocEvent(BDLocation event) {
        view.refreshLoc(event);
    }

    //处理调度中心返回的消息
    @Subscribe
    public void handControlEvent(ControlCenterEvent event) {
        String action = event.getAction();
        if (Constants.ACTION_CONTROL_RESPONSE_COMMON.equals(action)) {
            view.disTipDialog();
            CmdCommonResponse commonResponse = (CmdCommonResponse) event.getResponse();
            if (commonResponse.getMsgID().equals(Protocl.CMD_SEND_JK)) {
                LogUtil.log("order", "开始预约单返回结果：" + commonResponse.toString());
                if (commonResponse.getResult() == 0) {
                    orderStatusChanged(Constants.STATUS_ORDER_QJCK);
                    refreshView();
                } else {
                    view.showTipTost("您有正在进行中的订单，不能开始本订单!");
                }
            } else if (commonResponse.getMsgID().equals(Protocl.CMD_SEND_CKSC)) {
                orderStatusChanged(Constants.STATUS_ORDER_CKSC);
                refreshView();
            } else if (commonResponse.getMsgID().equals(Protocl.CMD_SEND_FINSH)) {
                orderStatusChanged(Constants.STATUS_ORDER_FINISH);
                if (AppManger.getInstance().isYzc()) {
//                    view.showTipProg("获取数据中，请稍候..");
                } else {
                    view.disTipDialog();
                    TtsManger.getInstance().speak("订单完成");
                    view.finishAty();
                }
            } else if (commonResponse.getMsgID().equals(Protocl.CMD_SEND_CANCLE)) {
                orderStatusChanged(Constants.STATUS_ORDER_CANCLE);
                refreshView();
            }
        } else if (Constants.ACTION_CONTROL_RESPONSE_ZXQXDD.equals(action)) {
            CmdZxQxDdResponse zxQxDdResponse = (CmdZxQxDdResponse) event.getResponse();
            if (order.getOrderID().equals(zxQxDdResponse.getOrderSno())) {
                TtsManger.getInstance().speak("订单取消");
                orderStatusChanged(Constants.STATUS_ORDER_CANCLE);
                refreshView();

                view.finishAty();
            }
        } else if (Constants.ACTION_CONTROL_RESPONSE_COST.equals(action)) {
            view.disTipDialog();
            view.goOrderPayPage(order);
        }
    }

    //处理订单费用事件
    @Subscribe
    public void handOrderCostEvent(OrderCostEvent event) {
        if (event != null && event.getCost() != null)
            view.refreshJfMsg(event.getCost());
    }

    //处理获取订单详情的事件
    @Subscribe
    public void handOrderDetailsEvent(OrderDetailsEvent event) {
        view.disTipDialog();
        if (event != null && event.getOrder() != null) {
            this.order = event.getOrder();
            LogUtil.log("applog", "订单详情:" + order.toString());
            view.refershCommonView(event.getOrder());
            refreshView(true);
        } else {

        }
    }

    //初始化算路
    private void initRoute() {
        routePlanSearch = RoutePlanSearch.newInstance();
        routePlanSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
                if (drivingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    LogUtil.log(OrderDetailsPresenterImpl.class, "起终点或途经点地址有岐义，通过以下接口获取建议查询信息");
                    // result.getSuggestAddrInfo()
                    return;
                }
                LogUtil.log(OrderDetailsPresenterImpl.class, "获取规划路线0:" + drivingRouteResult.error);
                if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    LogUtil.log(OrderDetailsActivity.class, "获取规划路线");
                    view.refreshRoutPlan(drivingRouteResult);
                }
            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }
        });
    }

    //根据订单状态重新刷新页面
    private void refreshView(boolean... isFrist) {
        if (order == null)
            return;
        if (order.getOrderStatus() == Constants.STATUS_ORDER_CREATE) {
            view.showStartYYD(order);
        } else if (order.getOrderStatus() == Constants.STATUS_ORDER_QJCK) {
            navSet(order.getPassgerLat(), order.getPassgerLng(), "");
            if (AppManger.getInstance().currentLocation != null)
                searchRoute(new LatLng(AppManger.getInstance().currentLocation.getLatitude(), AppManger.getInstance().currentLocation.getLongitude()),
                        new LatLng(Double.parseDouble(order.getPassgerLat()), Double.parseDouble(order.getPassgerLng())));
            view.showQjCk();
        } else if (order.getOrderStatus() == Constants.STATUS_ORDER_CKSC) {
            LogUtil.log("order", "乘客上车");
            navSet(order.getEndLat(), order.getEndLng(), "");
            if ((!StringUtils.isEmpty(order.getEndLat())) && (!StringUtils.isEmpty(order.getEndLat())))
                searchRoute(new LatLng(Double.parseDouble(order.getPassgerLat()), Double.parseDouble(order.getPassgerLng())),
                        new LatLng(Double.parseDouble(order.getEndLat()), Double.parseDouble(order.getEndLng())));
            view.shwoInCar();

            if (AppManger.getInstance().isYzc()) {
                if (BaseApplication.getInstance().mainService != null)
                    BaseApplication.getInstance().mainService.requestSendLoc();

                view.startRefreshOrderCost();
            }

        } else if (order.getOrderStatus() == Constants.STATUS_ORDER_FINISH) {
            if ("3".equals(order.getLocalStatus()) && AppManger.getInstance().isYzc()
                    && order.getPayStatus() == -1) {
                view.goOrderPayPage(order);
            } else
                view.showOrderFinsh(order);
        } else if (order.getOrderStatus() == Constants.STATUS_ORDER_CANCLE) {
            if (isFrist.length > 0 && isFrist[0])
                view.showOrderFinsh(order);
            else view.showDdQx();
        }
    }

    /* 修改订单状态*/
    private void orderStatusChanged(int status) {
        order.setOrderStatus(status);
    }

    //设置导航的始终点
    private void navSet(String endLat, String endLng, String endAddr) {
        BDLocation currentLocation = AppManger.getInstance().currentLocation;
        if (currentLocation != null)
            navSet(currentLocation.getLatitude() + "", currentLocation.getLongitude() + "", "", endLat, endLng, endAddr);
        else
            navSet("", "", "", "", "", "");
    }

    private void navSet(String startLat, String startLng, String startAddr, String endLat, String endLng, String endAddr) {
        startAddress = null;
        endAddress = null;

        if (StringUtils.isEmpty(startLat) || StringUtils.isEmpty(startLng) || StringUtils.isEmpty(endLat) || StringUtils.isEmpty(endLng))
            return;

        startAddress = new NavAddressInfo(startLat, startLng, startAddr);
        endAddress = new NavAddressInfo(endLat, endLng, endAddr);
    }
}
